#setLanguageLevel 4;

//Script: Company to Visma Net - version 03-01-2025 13:00 by SuperOffice InfoBridge

//--Configuration start
//This is the only part of the script where configuration per tenant is needed.
//In variables and other code we use Contact for company (UI and documentation) 
//and we use Person for a contact (UI and documentation). 

//The user friendly name of the ERP system.
String erpPlatform = "Visma Net";

//You can find the INSTANT job URL in the Process step of the DataBridge Integration. (Note: make sure to take the INSTANT job URL).
String instantJobUrl = "";

//The user defined field that indicates if a company card is linked to a company card in ERP. Fill in the Prog ID.
//A bool will be checked for 0/1; a text or number will be checked whether the field is empty.
String fieldContactIsLinkedToERP = "COMPANYLINKEDTOERP";

//--Configuration end


EventData ed = getEventData();
String contactId = ed.getInputValue("ContactEntity.ContactId");
String contactName = ed.getInputValue("ContactEntity.Name");
String personId = ed.getInputValue("ContactEntity.SupportPerson.PersonId");
String personName = ed.getInputValue("ContactEntity.SupportPerson.FullName");
String contactIsLinkedToERP_Value = ed.getInputValue("ContactEntity.CustomFields." + fieldContactIsLinkedToERP);
Bool contactIsLinkedToERP = false;

//Check if the company is already sent to ERP.
if (!contactIsLinkedToERP_Value.isEmpty() && contactIsLinkedToERP_Value.after("[").until(":") == "I")
{
    if (!contactIsLinkedToERP_Value.after(":").until("]").isNumber())
    {
        contactIsLinkedToERP = true;
    }
    else if (contactIsLinkedToERP_Value.after(":").until("]").toInteger() > 0)
    {
        contactIsLinkedToERP = true;
    }
}
String contactOperation;
if (contactIsLinkedToERP) {contactOperation = "updated";} else {contactOperation = "created";}

//Updates from SuperOffice to ERP are not allowed
if (contactIsLinkedToERP)
{
    ed.setMessage("\r\nThe company '" + contactName +"' is already available in " + erpPlatform + " and cannot be updated from SuperOffice.");
}
else if (!contactId.isEmpty() && contactId.toInteger() > 0 && !contactName.isEmpty() && !personId.isEmpty() && personId.toInteger() > 0 && !personName.isEmpty()) 
{
    //Call the DataBridge instant job and wait for its response.
    try {
        HTTP h;
        XMLNode root = parseJSON(String(h.get(instantJobUrl + "&PersonId=" + personId)));
        String linesProcessed = root.getValueFromPath("LinesProcessed");

        if (!linesProcessed.isEmpty() && linesProcessed.toInteger() >= 1)
        {
            ed.setMessage("\r\nThe company '" + contactName +"' is " + contactOperation + ".");
            
            //Set the 'Is linked to ERP' field to 'True'
            NSContactAgent agent;
            NSContactEntity contact = agent.GetContactEntity(contactId.toInteger());
            Map fields;
            fields.insert(fieldContactIsLinkedToERP, "[I:1]");
            contact.SetUserDefinedFields(fields);
            agent.SaveContactEntity(contact);

        }
        else
        {
            ed.setMessage("\r\nThe company '" + contactName +"' could not be " + contactOperation + ".\r\n\r\nCheck the values in " + erpPlatform + ".");
        }

    }
    catch {
        ed.setMessage("Exception: \r\n" + error);
    }

}
else 
{
  ed.setMessage("\r\nThe company details could not be found or the primary contact is not set.\r\n\r\nThe company was not " + contactOperation + " in " + erpPlatform + ".");
}

ed.setBlockExecution(true);
